import React, {useEffect, useRef, useState} from "react";
import {Button, Form, Icon, Input, Modal, Popconfirm, Row, Select, Table} from "antd";
import UserEditPopup from "./components/UserEditPopup";
import {addUserToServer, deleteUser, getUserList, updateUser} from "../../api/users";

const {Option} = Select;
const UserControl = function (props) {
	const popupRef = useRef(null);
	const [confirmLoading, setConfirmLoading] = useState(false);
	const [loading, setLoading] = useState(true);
	// const [stationDist, setStationDist] = useState({});
	const columns = [
		{
			title: "姓名",
			dataIndex: "name",
			key: "name"
		},
		{
			title: "账号",
			dataIndex: "username",
			key: "username"
		},
		{
			title: "岗位",
			dataIndex: "groups_detail",
			key: "groups_detail",
			render: groups => {
				return groups[0].name
			}
		},
		{
			title: "性别",
			dataIndex: "gender",
			key: "gender",
			render: gender => {
				return gender === "male" ? "男" : "女";
			}
		},
		{
			title: "地址",
			dataIndex: "address",
			key: "address",
			render: address => {
				return address || "-";
			}
		},
		{
			title: "座机",
			dataIndex: "landline_number",
			key: "landline_number",
			render: tel => {
				return tel || "-";
			}
		},
		{
			title: "电话",
			dataIndex: "telephone_number",
			key: "telephone_number",
			render: mobile => mobile || "-"
		},
		{
			title: "微信",
			dataIndex: "wechat_id",
			key: "wechat_id",
			render: wechat => wechat || "-"
		},
		{
			title: "邮箱",
			dataIndex: "email",
			key: "email",
			render: email => email || "-"
		},
		{
			title: "操作",
			dataIndex: "operation",
			key: "operation",
			render: (text, record) => {
				const click = e => {
					let {id} = record;
					setOriginUserInfo(record);

					console.log('record', record);
					setShowModal(true);
					setTimeout(() => {
						popupRef.current().initFormValue(record);
					}, 0);
				};
				return (
					<>
						<Icon type={'edit'} onClick={click}/>


						<Popconfirm title={'确定删除当前用户吗？'} onConfirm={() => {
							deleteUser(record.id).then((res => {
								initTable()
							}))
						}}>
							<Icon type="delete" style={{marginLeft: '20px'}}/>

						</Popconfirm>


					</>
				)
			}
		}
	];


	const [userData, setUserData] = useState([]);
	const [showModal, setShowModal] = useState(false);
	const [originUserInfo, setOriginUserInfo] = useState({});
	const [formForSerach, setFormForSerach] = useState({
		order: "", page: 1, page_size: 10
	});

	// const [pageInfo, setPageInfo] = useState({start: 0, limit: 10});
	const [dataTotal, setDataTotal] = useState(0);
	const [selectedRowKeys, setSelectedRowKeys] = useState([]);

	function initTable() {
		getUserList(formForSerach).then((res) => {
			setDataTotal(res.count)
			setUserData(res.results)
			setLoading(false)
			// console.log('users', res);
		})
	}

	useEffect(() => {
		let didCancel = false;
		if (!didCancel) {
			initTable();
		}
		return () => {
			didCancel = true;
		};
	}, [formForSerach]);

	const handleSubmit = e => {
		e.preventDefault();
		let values = props.form.getFieldsValue();
		// console.log(values)
		// initTable()
		setFormForSerach({...values});
	};
	const handleClear = () => {
		props.form.resetFields();
		initTable()
	};
	const watchPaginationChange = (curPageNum, pageSize) => {
		/*setPageInfo(prePageInfo => {
			return Object.assign({}, prePageInfo, {
				start: curPageNum,
				limit: pageSize
			});
		});*/
		setFormForSerach({
			page: curPageNum
		})
	};

	const addUser = () => {
		setShowModal(true);
	};


	const handleModalCancel = () => {
		setShowModal(false);
	};

	const postForm = () => {
		setConfirmLoading(true);
		let {value: formValue, isEdit} = popupRef.current().getFormValue(); //isEdit,判断数据来源是来自于新增还是添加。新增和添加用的是两个不同的接口。
		if (!isEdit) {
			handleAddUser(formValue);
		} else {
			handleEditUser(formValue);
		}
	};
	const handleEditUser = formValue => {
		const postUser = {...originUserInfo, ...formValue, groups: [formValue.groups]}
		console.log(postUser);
		updateUser(postUser).then((res) => {
			if (res) {
				setConfirmLoading(false)
				setShowModal(false)
				initTable()
			}
		})
	};
	const handleAddUser = formValue => {
		console.log(formValue);
		const postValue = {...formValue, groups: [formValue.groups]}

		addUserToServer(postValue).then((res => {
			if (res) {
				setConfirmLoading(false)
				setShowModal(false)
				initTable()
			}
		}))
	};


	const handleModalOk = () => {
		let canPost = popupRef.current().validateFields();
		if (!canPost) {
			return;
		}
		postForm();

	};

	const onRef = ref => {
		popupRef.current = ref;
	};

	const {getFieldDecorator} = props.form;

	return (
		<React.Fragment>
			<Row>
				<Form onSubmit={handleSubmit} layout="inline">
					<Form.Item label="姓名">
						{getFieldDecorator("name", {})(<Input/>)}
					</Form.Item>
					<Form.Item label="登录账号">
						{getFieldDecorator("username", {})(<Input/>)}
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							搜索
						</Button>
					</Form.Item>
					<Form.Item>
						<Button onClick={handleClear}>清空</Button>
					</Form.Item>
					<Form.Item>
						<Button type="primary" onClick={addUser}>
							添加
						</Button>
					</Form.Item>
				</Form>

			</Row>

			<Row style={{backgroundColor: "#fff"}}>
				<Table
					loading={loading}
					dataSource={userData}
					columns={columns}
					pagination={{
						current: formForSerach.page,
						// showSizeChanger: true,
						total: dataTotal,
						// showTotal: (total, range) =>
						// 	`${range[0]}-${range[1]} of ${total} items`,
						defaultPageSize: formForSerach.page_size,
						// onShowSizeChange: watchPaginationChange,
						onChange: watchPaginationChange
					}}
					rowKey={record => record.id}
					bordered
				></Table>
			</Row>
			<Modal
				confirmLoading={confirmLoading}
				closable={false}
				visible={showModal}
				onOk={handleModalOk}
				onCancel={handleModalCancel}
				destroyOnClose={true}
			>
				<UserEditPopup onRef={onRef}></UserEditPopup>
			</Modal>
		</React.Fragment>
	);
};

const UserControlForm = Form.create()(UserControl);

export default UserControlForm;
